import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Button, Spin, message } from 'antd';
import { 
  BellOutlined, 
  FileOutlined, 
  IssueOutlined, 
  UserOutlined, 
  BugOutlined, 
  CheckCircleOutlined, 
  ClockCircleOutlined, 
  PlusOutlined 
} from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import api from '../services/api';
import { useUser } from '../contexts/UserContext';

const DashboardPage = () => {
  console.log('DashboardPage组件开始渲染');
  
  const [stats, setStats] = useState({
    total_issues: 0,
    resolved_issues: 0,
    open_issues: 0,
    today_new: 0
  });
  const [loading, setLoading] = useState(false);
  const [recentIssues, setRecentIssues] = useState([]);
  const history = useHistory();
  const { user, hasPermission } = useUser();

  console.log('DashboardPage状态:', { stats, loading, user });

  // 获取统计信息
  const fetchStats = async () => {
    setLoading(true);
    try {
      // 获取问题统计
      const issuesResponse = await api.get('/issues');
      const issues = issuesResponse.data;
      
      const total_issues = issues.length;
      const resolved_issues = issues.filter(issue => issue.status === 'resolved').length;
      const open_issues = issues.filter(issue => issue.status === 'open').length;
      
      // 获取今日新增问题
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const today_new = issues.filter(issue => {
        const createdDate = new Date(issue.created_at);
        return createdDate >= today;
      }).length;
      
      setStats({
        total_issues,
        resolved_issues,
        open_issues,
        today_new
      });
      
      // 设置近期问题（取最新的5个）
      const recentIssuesData = issues
        .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
        .slice(0, 5);
      setRecentIssues(recentIssuesData);
      
    } catch (error) {
      console.error('获取统计信息失败:', error);
      message.error('获取统计信息失败');
      
      // 如果接口失败，使用模拟数据
      const mockIssues = [
        {
          id: 1,
          title: '设备无法启动',
          status: 'open',
          priority: 'high',
          created_at: new Date().toISOString(),
          submitter: '张三'
        },
        {
          id: 2,
          title: '软件界面无响应',
          status: 'in_progress',
          priority: 'medium',
          created_at: new Date(Date.now() - 86400000).toISOString(), // 昨天
          submitter: '李四'
        },
        {
          id: 3,
          title: '网络连接失败',
          status: 'resolved',
          priority: 'low',
          created_at: new Date(Date.now() - 172800000).toISOString(), // 前天
          submitter: '王五'
        }
      ];
      
      setStats({
        total_issues: 3,
        resolved_issues: 1,
        open_issues: 2,
        today_new: 1
      });
      setRecentIssues(mockIssues);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStats();
  }, []);

  const statCards = [
    { title: '总问题数', value: stats.total_issues, icon: <BugOutlined />, color: '#1890ff' },
    { title: '已解决', value: stats.resolved_issues, icon: <CheckCircleOutlined />, color: '#52c41a' },
    { title: '待处理', value: stats.open_issues, icon: <ClockCircleOutlined />, color: '#fa8c16' },
    { title: '今日新增', value: stats.today_new, icon: <PlusOutlined />, color: '#722ed1' }
  ];

  return (
    <div>
      <h2>仪表板</h2>
      
      {loading ? (
        <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />
      ) : (
        <>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            {statCards.map((stat, index) => (
              <Col span={6} key={index}>
                <Card>
                  <Statistic
                    title={stat.title}
                    value={stat.value}
                    prefix={stat.icon}
                    valueStyle={{ color: stat.color }}
                  />
                </Card>
              </Col>
            ))}
          </Row>
          
          <Row gutter={16}>
            <Col span={16}>
              <Card 
                title="近期问题" 
                extra={<Button type="primary" onClick={() => history.push('/issues')}>查看更多</Button>}
              >
                {recentIssues.length === 0 ? (
                  <p style={{ textAlign: 'center', color: '#999' }}>暂无近期问题</p>
                ) : (
                  <div>
                    {recentIssues.map(issue => (
                      <div 
                        key={issue.id}
                        style={{ 
                          padding: '12px 0', 
                          borderBottom: '1px solid #f0f0f0',
                          cursor: 'pointer'
                        }}
                        onClick={() => history.push(`/issues/${issue.id}`)}
                      >
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <div style={{ flex: 1 }}>
                            <h4 style={{ margin: 0, fontSize: '14px' }}>{issue.title}</h4>
                            <p style={{ margin: '4px 0 0 0', fontSize: '12px', color: '#666' }}>
                              提交人: {issue.submitter} | 时间: {new Date(issue.created_at).toLocaleDateString()}
                            </p>
                          </div>
                          <div style={{ display: 'flex', gap: '8px' }}>
                            <span style={{
                              padding: '2px 8px',
                              borderRadius: '4px',
                              fontSize: '12px',
                              backgroundColor: issue.priority === 'high' ? '#ff4d4f' : 
                                             issue.priority === 'medium' ? '#fa8c16' : '#52c41a',
                              color: 'white'
                            }}>
                              {issue.priority === 'high' ? '高' : 
                               issue.priority === 'medium' ? '中' : '低'}
                            </span>
                            <span style={{
                              padding: '2px 8px',
                              borderRadius: '4px',
                              fontSize: '12px',
                              backgroundColor: issue.status === 'open' ? '#1890ff' : 
                                             issue.status === 'in_progress' ? '#fa8c16' : '#52c41a',
                              color: 'white'
                            }}>
                              {issue.status === 'open' ? '待处理' : 
                               issue.status === 'in_progress' ? '处理中' : '已解决'}
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </Card>
            </Col>
            <Col span={8}>
              <Card title="快捷操作">
                {hasPermission('create_issue') && (
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />} 
                    block 
                    style={{ marginBottom: 16 }}
                    onClick={() => history.push('/create-issue')}
                  >
                    创建问题
                  </Button>
                )}
                {hasPermission('manage_cases') && (
                  <Button 
                    block 
                    style={{ marginBottom: 16 }}
                    onClick={() => history.push('/cases')}
                  >
                    查看案例库
                  </Button>
                )}
                {hasPermission('manage_resources') && (
                  <Button 
                    block
                    onClick={() => history.push('/resources')}
                  >
                    查看资源中心
                  </Button>
                )}
                
                {/* 用户角色信息显示 */}
                <div style={{ marginTop: 24, padding: '16px', backgroundColor: '#f8f9fa', borderRadius: '6px' }}>
                  <h4 style={{ margin: '0 0 8px 0', fontSize: '14px' }}>当前用户</h4>
                  <p style={{ margin: 0, fontSize: '12px', color: '#666' }}>
                    用户名: {user?.username || '未知'}<br/>
                    角色: {user?.role === 'admin' ? '管理员' : 
                           user?.role === 'engineer' ? '工程师' : '客户'}
                  </p>
                </div>
              </Card>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
};

export default DashboardPage;